import sys
import glob
import yaml
import os.path
import util
from optionServer import optionServer
from object import Object

class FileServer:
    def __init__(self):
        self.filePaths = {}
        self.modules = set()
        self.extFiles = {}
        
        self.loadFunctions = util.getFunctions(self, "load_")
        
    def loadModules(self):
        map(self.loadModule,filter(os.path.isdir,[arg.rstrip('/') for arg in sys.argv]))
        
    def loadFiles(self):
        for ext, files in self.extFiles.iteritems():
            if ext in self.loadFunctions:
                map(self.loadFunctions[ext],files)
        
    def loadModule(self, name):
        if name not in self.modules:
            self.modules.add(name)
            print "load module", name
            
            for path in self.searchFiles(name):
                filename = path.split('/')[-1]
                ext = filename.split('.')[-1]
                self.filePaths[filename] = path
                self.extFiles.setdefault(ext,set()).add(path)
            
    def searchFiles(self, path, pattern = '*'):
        files = filter(os.path.isfile,glob.glob(path + "/" + pattern))
        
        for subPath in filter(os.path.isdir,glob.glob(path + "/*")):
            files.extend(self.searchFiles(subPath,pattern))
            
        return files
        
    def getFile(self, filename):
        return self.filePaths.get(filename)
        
    def load_cfg(self, filename):
        optionServer.update(yaml.evalLoad(open(filename)))
        
    def load_sim(self, filename):
        for name, vals in yaml.evalLoad(open(filename)).iteritems():
            Object(name,**vals)

fileServer = FileServer()
